package utils;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    //定义一个数据源对象
    private static DataSource dataSource;
    //定义URL
    private static String URL="";
    //定义用户名
    private static String USER="root";
    //定义密码
    private static String PASSWORD="123456";

    //在类加载的时候初始化dataSourse对象
    static{
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);
        dataSource=mysqlDataSource;
    }


    //构造方法私有化，防止其他的地方通过new来创建这个类的对象
    private DBUtil(){}


    /*获取数据库连接*/
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }


    /*释放资源*/
    public static void close(ResultSet resultSet, Statement statement,Connection connection){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
